// @Title  modbus.go
// @Description  使用modbus汇总进行数据采集
// @Author  IT搬运工
// @Update
package gather

import (
	"intelligentgateway/src/container"
	"intelligentgateway/src/entity"
	"intelligentgateway/src/server"
	"time"

	"github.com/things-go/go-modbus"
	"google.golang.org/protobuf/proto"
)

//发送A-BMS和HVM的数据
func SendABMSAndHVMData(aBmsModbusPoint *server.ModbusPoint, aHvmModbusPoint *server.ModbusPoint, client modbus.Client, channel chan []byte, channelId string, sn string) {
	//if nil == aBmsModbusPoint || nil == aHvmModbusPoint {
	if nil == aBmsModbusPoint {
		return
	}
	timer := time.NewTicker(time.Duration(aBmsModbusPoint.CollectInterval) * time.Second)
	defer timer.Stop()
	for range timer.C {
		//获取A-BMS的数据
		reusultMap, err := collectData(aBmsModbusPoint, client)
		if nil != err {
			return
		}
		msg := &entity.ABMSMsg{}
		msg.Id = sn

		value, ok := reusultMap["Current#0"]
		if ok {
			msg.Current = value
		}

		//发送数据到通道中
		data, err := proto.Marshal(msg)
		if nil != err {
			break
		}
		channelStatus, ok := container.Get(channelId)
		if !ok {
			break
		}
		status := channelStatus.(*container.ChannelStatus)
		if status.IsRun {
			channel <- data
		} else {
			//结束采集
			break
		}

	}

}

//采集数据
func collectData(point *server.ModbusPoint, client modbus.Client) (map[string]float32, error) {
	itemMap := make(map[string]float32)
	for _, item := range point.Items {
		result, err := client.ReadHoldingRegisters(1, uint16(item.BaseAddr), uint16(item.Quantity))
		if err != nil {
			return nil, err
		}

		for index, value := range result {
			itemMap[item.Keys[index]] = float32(value) / float32(item.Magnification[index])
		}
	}
	return itemMap, nil
}
